/*
 * Copyright (C) 2011 The Android Open Source Project
 * Copyright (C) 2011 Jake Wharton
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.letv.android.client.view.channel;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.letv.android.young.client.R;
import com.letv.android.client.view.title.TabPageIndicator;
import com.letv.core.utils.UIsUtils;

/**
 * 频道导航栏索引
 *
 */
@SuppressLint("ResourceAsColor")
public class ChannelTabPageIndicator extends TabPageIndicator {
    // 当tab数大于该值时，tab的宽度将根据自己的文字长度进行计算，否则所有的tab宽度相同
    private static final int MAX_TABS = 7;
    // tab的间距
//    private static final int TAB_MARGIN = UIsUtils.dipToPx(6);
    private static final int TAB_MARGIN = 6;
    // 整个导航栏的宽度
    private int mLayoutWidh = 0;
    // 平均宽度
    private int mMeanWidth = -1;

    public ChannelTabPageIndicator(Context context) {
        this(context, null);
    }

    public ChannelTabPageIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        setAutoWidth(false);
        mIsCustomTabWidth = true;
    }

    /**
     * 设置导航栏的宽度
     * 
     * @param width
     */
    public void setWidth(int width) {
        if (width > 0) {
            mLayoutWidh = width;
            setLayoutParams(new RelativeLayout.LayoutParams(mLayoutWidh, UIsUtils.dipToPx(mContext,45)));
        }
    }

    @Override
    public void notifyDataSetChanged() {
        // 计算item的宽度
        PagerAdapter adapter = mViewPager.getAdapter();
        final int count = adapter.getCount();
        if (count == 0)
            return;
        int width = TAB_MARGIN;
        for (int i = 0; i < count; i++) {
            CharSequence title = adapter.getPageTitle(i);
            width += getTabWidth(title) + TAB_MARGIN;
        }
        mMeanWidth = -1;
        if (mLayoutWidh > width && count <= MAX_TABS) {
            mMeanWidth = (mLayoutWidh - TAB_MARGIN * (count + 1)) / count;
        }
        super.notifyDataSetChanged();
    }

    @Override
    protected void addTab(int index, CharSequence text, int iconResId) {
        final TabView tabView = new TabView(getContext(), text);
        tabView.setIndex(index);
        tabView.setFocusable(true);
        tabView.setOnClickListener(mTabClickListener);
        if (mContext.getString(R.string.vip_tag).equals(text)) {
            tabView.setTextColor(mContext.getResources().getColor(R.color.letv_color_ffff0000));
        }
        if (iconResId != 0) {
            tabView.setCompoundDrawablesWithIntrinsicBounds(iconResId, 0, 0, 0);
        }
        LinearLayout.LayoutParams params = null;
        int width = mMeanWidth == -1 ? tabView.getCustomWidth() : mMeanWidth;
        if (mMeanWidth != -1) {
            tabView.setSize(mMeanWidth, TAB_HEIGHT);
        }
        params = new LinearLayout.LayoutParams(width, tabView.getCustomHeight(), Gravity.CENTER);
        params.setMargins(TAB_MARGIN, 0, TAB_MARGIN, 0);
        mTabLayout.addView(tabView, params);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void setCurrentItem(int item) {
        if (mViewPager == null) {
            return;
        }
        if (item != -1 && mSelectedTabIndex != item) {
            mViewPager.setCurrentItem(item);
        }
        mSelectedTabIndex = item;

        final int tabCount = mTabLayout.getChildCount();
        for (int i = 0; i < tabCount; i++) {
            final View child = mTabLayout.getChildAt(i);
            final boolean isSelected = (i == item);
            child.setSelected(isSelected);
            if (isSelected) {
                animateToTab(item);
                ((TabView) child).setTextColor(mContext.getResources().getColor(R.color.letv_color_ff5895ed));
                child.setBackgroundResource(R.drawable.letv_tab_indicator_bg);
            } else {
                if (mContext.getString(R.string.vip_tag).equals(((TabView) child).getText())) {
                    ((TabView) child).setTextColor(mContext.getResources().getColor(R.color.letv_color_ffff0000));
                } else {
                    ((TabView) child).setTextColor(mContext.getResources().getColor(R.color.letv_color_ff444444));
                }
                child.setBackgroundDrawable(null);
            }

            if (i == 0 && child instanceof FrameLayout) {
                ((FrameLayout) child).getChildAt(0).setBackgroundDrawable(null);
            }
        }
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mIsCustomTabWidth) {
            setFillViewport(false);
        }
    }

    private final OnClickListener mTabClickListener = new OnClickListener() {
        public void onClick(View view) {
            TabView tabView = (TabView) view;
            final int newSelected = tabView.getIndex();
            if (mTabReselectedListener != null) {
                if (mViewPager.getCurrentItem() == newSelected) {
                    mTabReselectedListener.onTabReselected(newSelected);
                }
                mTabReselectedListener.dismissWindow();
            }
            setCurrentItem(newSelected);

            // 统计频道二级导航中的点击统计-5.5版本
//            if (mViewPager != null && mViewPager.getAdapter() instanceof ChannelDetailPagerAdapter) {
//                String name = ((ChannelDetailPagerAdapter) mViewPager.getAdapter()).getPageTitle(newSelected) + "";
//                String pageid = ((ChannelDetailPagerAdapter) mViewPager.getAdapter()).getPageId(newSelected) + "";
//                String cid = ((ChannelDetailPagerAdapter) mViewPager.getAdapter()).getCid(newSelected) + "";
//                StatisticsUtils.staticticsInfoPostAddScid(mContext, "0", "h11", name, newSelected + 1, null,
//                        PageIdConstant.getPageIdByChannelId(Integer.valueOf(cid)), cid + "", null, null, null, null,
//                        pageid);
//                LogInfo.LogStatistics("Tab点击:" + name + "-----" + pageid);
//            }
        }
    };
}
